package com.example.rubbish.Fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.rubbish.Adapter.RecordAdapter;
import com.example.rubbish.DataBase.RDataBase;
import com.example.rubbish.DataBase.Record;
import com.example.rubbish.MainActivity;
import com.example.rubbish.R;
import com.example.rubbish.ResultActivity;
import com.example.rubbish.Ui.ReviseDialogView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;


public class RecordFragment extends Fragment {
    private View root;

    SwipeRefreshLayout swipeRefreshLayout;
    private ListView listView;
    //    private RecyclerView recyclerView;
    private RDataBase db;
    private RecordAdapter viewAdapter;
    //    private RecordViewAdapter viewAdapter;
    private AlertDialog alertDialog;
    private FloatingActionButton button_add;

    private List<Record> records= new ArrayList<>();
//    private List<String> textList ;
//    private  List<List<String>> itemList = new ArrayList<>();


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        root = inflater.inflate(R.layout.fragment_record, container, false);
        swipeRefreshLayout = root.findViewById(R.id.freshLayout);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        listView = root.findViewById(R.id.record_recyclerView);
        db = RDataBase.getInstance(getContext());
        button_add = root.findViewById(R.id.button_add);

        records = initDataList();
//        viewAdapter = new RecordViewAdapter(itemList);
//        recyclerView.setLayoutManager(layoutManager);
//        setAdapterListener();
        viewAdapter = new RecordAdapter(root.getContext(), R.layout.record_item, records);
        listView.setAdapter(viewAdapter);

        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.orange));


        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setListViewListener();
        setSwipeFreshListener();
        setButtonListener();

    }

    private List<Record> initDataList() {
        return db.loadRecord();
    }

    private void setButtonListener() {
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showEditDialog();

            }
        });

    }

    private void showEditDialog() {
        ReviseDialogView reviseDialogView1 = new ReviseDialogView(root.getContext());
        EditText edit_date = reviseDialogView1.findViewById(R.id.revise_date);
        EditText edit_garbage = reviseDialogView1.findViewById(R.id.revise_garbageName);
        EditText edit_cate = reviseDialogView1.findViewById(R.id.revise_cateName);
        alertDialog = new AlertDialog.Builder(root.getContext())
                .setTitle("新记录")
                .setView(reviseDialogView1)
                .setPositiveButton("确定保存(*^▽^*)", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //保存
                        String garbage = edit_garbage.getText().toString();
                        String cate = edit_cate.getText().toString();
                        String date = edit_date.getText().toString();
                        Record record = new Record();
                        record.setGarbageName(garbage);
                        record.setCateName(cate);
                        record.setTime(date);

//                        records.add( record);
                        db.saveResult(record);

                        viewAdapter.addItem(record);
//                        viewAdapter.notifyDataSetChanged();
                        Toast.makeText(getContext(), "添加成功", Toast.LENGTH_LONG).show();
                    }
                })
                .create();
        alertDialog.show();

    }


    private void setSwipeFreshListener() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshList();
            }
        });
    }

    private void setListViewListener() {
        //点击
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Record record = records.get(position);
                JumpToResult(record.getGarbageName());
            }
        });
        //长按
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                myPopupMenu(view, position);
                return true;
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                boolean enable = false;
                if (listView != null && listView.getChildCount() > 0) {
                    boolean firstItemVisible = (listView.getFirstVisiblePosition() == 0);
                    boolean topOfFirstItemVisible = (listView.getChildAt(0).getTop() == 0);
                    enable = firstItemVisible && topOfFirstItemVisible;
                    swipeRefreshLayout.setEnabled(enable);
                }
            }
        });
    }

    private void JumpToResult(String searchContent) {
        Intent intent = new Intent(getContext(), ResultActivity.class);
        intent.putExtra("searchContent", searchContent);
        intent.putExtra("searchType",0);
        startActivity(intent);

    }

    private void myPopupMenu(View v, int position) {
        PopupMenu popupMenu = new PopupMenu(getContext(), v);
        //设置布局
        popupMenu.getMenuInflater().inflate(R.menu.record_operation_menu, popupMenu.getMenu());
        //设置点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getTitle().toString()) {
                    case "删除":
                        Record record =records.get(position);

                        records.remove(position);
                       viewAdapter.removeItem(record);
                       viewAdapter.notifyDataSetChanged();
                        db.remove(record);
                        Toast.makeText(getContext(), "删除成功", Toast.LENGTH_LONG).show();



                        break;
                    case "修改":
                        showReviseDialog(v, position);
                        break;

                }
                return true;
            }
        });
        popupMenu.show();
    }

    private void showReviseDialog(View view, int position) {
        ReviseDialogView reviseDialogView = new ReviseDialogView(root.getContext());
        EditText edit_date = reviseDialogView.findViewById(R.id.revise_date);
        EditText edit_garbage = reviseDialogView.findViewById(R.id.revise_garbageName);
        EditText edit_cate = reviseDialogView.findViewById(R.id.revise_cateName);
        alertDialog = new AlertDialog.Builder(root.getContext())
                .setTitle("修改记录")
                .setView(reviseDialogView)
                .setPositiveButton("确定保存(*^▽^*)", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //保存
                        Record record = new Record();
                        record.setGarbageName(edit_garbage.getText().toString());
                        record.setCateName(edit_cate.getText().toString());
                        record.setTime(edit_date.getText().toString());

                        records.set(position, record);
                        viewAdapter.set(position, record);
                        viewAdapter.notifyDataSetChanged();
                        db.reviseResult(record);

                        Toast.makeText(getContext(), "修改成功", Toast.LENGTH_LONG).show();

                    }
                })
                .create();
        alertDialog.show();


    }

    private void refreshList() {
        records = initDataList();
        viewAdapter.setData(records);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ((MainActivity)(root.getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                        Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_LONG).show();
                    }
                });

            }
        }).start();

    }

    public  void  add(String garbage , String cate, String date){
        Record record = new Record();
        record.setGarbageName(garbage);
        record.setCateName(cate);
        record.setTime(date);
        db.saveResult(record);
        records.add(record);
    }

    @Override
    public void onPause() {
        super.onPause();
        records=db.loadRecord();
        viewAdapter.setData(records);
    }



}